package handler;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import dao.CompactDiscDao;

public class LoadEditDiscHandler implements ISetParamHandler{	
	private static final Logger LOGGER = Logger.getLogger(LoadEditDiscHandler.class);
	private static final String ERROR_MESSAGE_MISSING_PARAMS = "Parameters id,name,producer,type and data missing from the url";
	private static final String WRONG_FORMAT_DATE = "Data has wrong format";
	private static final DateFormat formatDate = new SimpleDateFormat("dd.MM.yyyy");

	private Long cdId = null;
	private String name = null;
	private String producer = null;
	private String type = null;
	private Date date = null;
	
	@Override
	public String setRequest(HttpServletRequest request) {
		String idcd = request.getParameter("idcd");
		name = request.getParameter("name");
		producer = request.getParameter("producer");
		type = request.getParameter("type");
		String dateString = request.getParameter("data");
		date = null;

		if(idcd == null || name == null || producer == null || type == null || dateString == null) {
			LOGGER.error(ERROR_MESSAGE_MISSING_PARAMS);
			return ERROR_MESSAGE_MISSING_PARAMS;
		}
		
		try {
			date = formatDate.parse(dateString);
			cdId = Long.parseLong(idcd);
		} catch (Exception e) {
			LOGGER.error(WRONG_FORMAT_DATE);
			return WRONG_FORMAT_DATE;
		};
		return "OK";
	}

	public String process() {
		String cdJson = null;
    	try {
    		cdJson = CompactDiscDao.updateCompactDisc(cdId, name, producer, type, date);
		} catch (Exception e) {
			return "Error on update cd" + e.getMessage();
		};
		return cdJson;
	}
	
}
